package com.wheat.common.result;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Optional;

/**
 * 数据返回类型
 *
 * @author wheat on 2019/12/5.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -6724401478874316373L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 描述信息
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;


    /**
     * 成功返回：data=null
     * {
     * "code": 200,
     * "msg": "执行成功",
     * "data": null
     * }
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> success() {
        return Result.success(RestfulCode.SUCCESS, null, null);
    }

    public static <T> Result<T> success(T data) {
        return Result.success(RestfulCode.SUCCESS, null, data);
    }

    public static <T> Result<T> success(RestfulCode rc, T data) {
        return Result.success(rc, null, data);
    }

    /**
     * 成功返回：有data返回值
     * {
     * "code": 200,
     * "msg": "执行成功",
     * "data": "zhang"
     * }
     *
     * @return
     */
    public static <T> Result<T> success(RestfulCode rc, String msg, T data) {
        return Result.<T>builder()
                .code(rc.getCode())
                .msg(Optional.ofNullable(msg).orElse(rc.getMessage()))
                .data(data)
                .build();
    }


    public static <T> Result<T> error() {
        return Result.success(RestfulCode.ERROR, null, null);
    }

    public static <T> Result<T> error(T data) {
        return Result.success(RestfulCode.ERROR, null, data);
    }

    public static <T> Result<T> error(String msg) {
        return Result.success(RestfulCode.ERROR, msg, null);
    }

    public static <T> Result<T> error(RestfulCode rc, T data) {
        return Result.success(rc, null, data);
    }


    public static <T> Result<T> error(RestfulCode rc, String msg, T data) {
        return Result.<T>builder()
                .code(rc.getCode())
                .msg(Optional.ofNullable(msg).orElse(rc.getMessage()))
                .data(data)
                .build();
    }
}
